package practice1.annotation;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import util.Schema;

public class MessageDAO {

	public static void main(String[] args) {

		// ########## unit 1 ：插入 ##############
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		Message message = new Message("Hello World");
		System.out.println(" >>> Unit1：执行持久化  <<<");
		session.save(message);
		System.out.println("\n");
		tx.commit();
		session.close();

		// ################### unit 2：查询 #############
		Session secondSession = HibernateUtil.getSessionFactory().openSession();

		System.out.println(" >>> Unit2：全表查询  <<<");
		List messages = secondSession.createQuery("from Message m order by m.text asc")
				.list();
		System.out.println(messages.size() + " message(s) found:");

		for (Iterator iter = messages.iterator(); iter.hasNext();) {
			Message loadedMsg = (Message) iter.next();
			System.out.println(loadedMsg.getText());
		}

		System.out.println("\n");
		secondSession.close();

		// ############### unit 3：修改　 ##########################
		Session thirdSession = HibernateUtil.getSessionFactory().openSession();
		Transaction thirdTransaction = thirdSession.beginTransaction();

		// message.getId() holds the identifier value of the first message
		System.out.println(">>> Unit3： 读取Unit1的记录  <<<");
		Message loadedMessage = (Message) thirdSession
				.get(Message.class, message.getId());
		System.out.println(" >>> 改写记录内容...");
		loadedMessage.setText("Greetings Earthling");
		loadedMessage.setNextMessage(new Message("Take me to your leader (please)"));
		System.out.println("\n");
		thirdTransaction.commit();
		thirdSession.close();

		// #################### Unit4 ：查询以验证修改生效  ######################
		Session fourthSession = HibernateUtil.getSessionFactory().openSession();
		Transaction fourthTransaction = fourthSession.beginTransaction();
		System.out.println(" >>> Final Unit：全表查询  <<< ");
		messages = fourthSession.createQuery("from Message m order by m.text asc").list();

		System.out.println(messages.size() + " message(s) found:");

		for (Iterator iter = messages.iterator(); iter.hasNext();) {
			Message loadedMsg = (Message) iter.next();
			System.out.println(loadedMsg.getText());
		}

		fourthTransaction.commit();
		fourthSession.close();

		// Shutting down the application
		HibernateUtil.shutdown();
		
		
		// #################### 查看schema  ######################
		System.out.println("\n >>> 查看 schema:  <<< ");
		Schema.getSchema();
	}
}
